package com.imesne.office.excel.write;

import com.imesne.office.excel.model.ExcelRange;
import com.imesne.office.excel.model.ExcelRow;
import com.imesne.office.excel.model.ExcelSheet;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;

import java.util.Collection;
import java.util.List;

/**
 * Created by liyd on 17/7/4.
 */
public class ExcelSheetWriterImpl extends AbstractConfigWriter implements ExcelSheetWriter {

    public Sheet writeExcelSheet(Workbook workbook, ExcelSheet excelSheet, int count) {

        ExcelWriterConfig excelWriterConfig = this.getExcelWriterConfig();
        Sheet sheet = null;
        if (excelWriterConfig.isAppend()) {
            int sheetIndex = excelSheet.getSheetNum() - 1;
            sheet = sheetIndex < workbook.getNumberOfSheets() ? workbook.getSheetAt(sheetIndex) : null;
            if (sheet == null && excelWriterConfig.isCloneSheetTemplate() && sheetIndex > 0) {
                sheet = workbook.cloneSheet(sheetIndex - 1);
            }
        }

        if (!excelWriterConfig.isAppend() || sheet == null) {
            sheet = workbook.createSheet();
        }
        int index = workbook.getSheetIndex(sheet);
        workbook.setSheetName(index, excelSheet.getSheetName());
        List<ExcelRange> mergedRegions = excelWriterConfig.getMergedRegions(excelSheet.getSheetNum());
        if (mergedRegions != null) {
            for (ExcelRange mergedRegion : mergedRegions) {
                //单元格范围 参数（int firstRow, int lastRow, int firstCol, int lastCol)
                CellRangeAddress cellRangeAddress = new CellRangeAddress(mergedRegion.getBeginRowNum() - 1, mergedRegion.getEndRowNum() - 1, mergedRegion.getBeginCellNum() - 1, mergedRegion.getEndCellNum() - 1);
                //在sheet里增加合并单元格
                sheet.addMergedRegion(cellRangeAddress);
            }
        }

        ExcelRowWriter excelRowWriter = excelWriterConfig.getExcelRowWriter();
        ExcelRow titleRow = excelSheet.getTitleRow();
        if (titleRow != null) {
            excelRowWriter.writeExcelTitleRow(workbook, sheet, titleRow);
        }
        Collection<ExcelRow> excelRows = excelSheet.getExcelRows();

        //移动页脚
        ExcelRange footer = excelWriterConfig.getFooter(excelSheet.getSheetNum());
        if (footer != null) {
            sheet.shiftRows(footer.getBeginRowNum() - 1, footer.getEndRowNum() - 1, excelRows.size() - footer.getPlaceholderRow());
        }

        for (ExcelRow excelRow : excelRows) {
            excelRowWriter.writeExcelRow(workbook, sheet, excelRow);
        }
        if (excelWriterConfig.getExcelWriteProcessor() != null) {
            excelWriterConfig.getExcelWriteProcessor().processSheet(excelSheet, sheet, workbook, count);
        }
        return sheet;
    }
}
